import router, { constantRoutes } from '@/router'
import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@js/config'
//VUE_APP_BASE_API = 'http://192.168.3.25:8086/api/'
//'https://mp2.teamotto.me/paralympic_tea/api'
// create an axios instance
const baseURL = process.env.NODE_ENV ==='development'?
  'https://mp2.teamotto.me/paralympic_tea/api'
 :process.env.VUE_APP_BASE_API
const service = axios.create({
  baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout,
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }

    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/x-www-form-urlencoded;charset=UTF-8'
    // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
      let data = config.data; let params = config.params; const dataN = {}
      if (data) {
          const tyN = typeof (data)
          if (tyN === 'object') {
            const dataN = {}
          for (var key in data) {
           if (data[key] || data[key] === 0) {
             dataN[key] = data[key]
           }
           }
           data = dataN
         }
      }
      if (params) {
          const tyP = typeof (params)
          if (tyP === 'object') {
            const paramsN = {}
          for (var keyN in params) {
           if (params[keyN] || params[keyN] === 0) {
             paramsN[keyN] = params[keyN]
           }
           }
           params = paramsN
         }
       }
    if ((config._transformRequest) && data) {
     config.transformRequest = [function(data) {
       const formData = new FormData()
       // debugger
         for (const key of Object.keys(data)) {
           var datas = data[key]
           const ty = typeof (datas)
           if (ty === 'object') {
            // debugger
             datas = JSON.stringify(datas)
           }
           if (datas) {
             formData.append(key, datas)
           }
         }
       return formData
       }]
     }

    config.data = data
    config.params = params
    // config.url = config.url + '?t=' + new Date().getTime()
    // debugger
    // config.data={};
    // config.params={}

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    log({ 'response\n': response })
    // console.log(response)
    if (res.code !== undefined) {
      res.status = res.code === 20000 ? 0 : res.code
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 0) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014 || res.status === 2002) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        Message({
          message: res.msg || 'Error',
          type: response.status ? 'warning' : 'success',
          duration: 5 * 1000
        })
        if (res.status === 2020) {
          router.push({ path: '/' })
        }
      }
     // return false
       return res
    } else {
      if (res.result && response.config.url.indexOf('course/obtain/course_info') <= -1) {
        if (res.result.list) {
          if (!res.result.list.length) {
            Message('No data')
          }
        }
      }
     return res
         }
  },
  error => {
    console.log('err', error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
